package cn.icare.cms.controller.restful;

import cn.icare.cms.*;
import cn.icare.cms.model.vo.rest.MsgDatasVO;
import cn.icare.cms.model.vo.rest.RespMsgVO;
import cn.icare.cms.model.vo.rest.UserVO;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class BaseController {

    @Resource
    private UserService userService;

    protected ResponseEntity<RespMsgVO> getRespOk() {
        return this.getRespOk(null);
    }

    protected ResponseEntity<RespMsgVO> getRespOk(Object resData) {
        RespMsgVO respMsgVO = new RespMsgVO(0, "请求处理成功", resData);
        return new ResponseEntity<>(respMsgVO, HttpStatus.OK);
    }

    protected ResponseEntity<RespMsgVO> getRespOkByPage(List datas) {
        MsgDatasVO msgDatasVO = new MsgDatasVO();
        msgDatasVO.setDatas(datas);
        if (ListUtil.isNotEmpty(datas)) {
            msgDatasVO.setTotal(datas.size());
        }
        return this.getRespOk(msgDatasVO);
    }

    protected ResponseEntity<RespMsgVO> getRespFail() {
        return this.getRespFail("请求处理失败");
    }

    protected ResponseEntity<RespMsgVO> getRespFail(String msg) {
        RespMsgVO respMsgVO = new RespMsgVO(1, msg, null);
        return new ResponseEntity<>(respMsgVO, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    protected ResponseEntity<RespMsgVO> getRespUnauthorized() {
        RespMsgVO respMsgVO = new RespMsgVO(401, "ss", null);
        return new ResponseEntity<>(respMsgVO, HttpStatus.UNAUTHORIZED);
    }

    protected UserVO getCurrentUser(HttpServletRequest request) {
        try {
            //  ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            //  HttpServletRequest httpServletRequest = servletRequestAttributes.getRequest();

            TokenUtil tokenUtil = new TokenUtil();
            String token = tokenUtil.getToken(request);
            if (StringUtil.isNotEmpty(token)) {
                JwtUtil jwtUtil = new JwtUtil();
                Integer userId = jwtUtil.parseJWT(token);
                if (userId > 0) {
                    return userService.getOne(userId);
                }
            }
        } catch (Exception ex) {
            return null;
        }
        return null;
    }

    protected String getCurrentUserName(HttpServletRequest request) {
        UserVO systemUser = getCurrentUser(request);
        String systemUserName = "";
        if (systemUser != null) {
            systemUserName = systemUser.getUsername();
        }
        return systemUserName;

    }
}
